/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dpy.appmvdpy.Models.Validators;

import com.dpy.appmvdpy.Facades.UsersFacade;
import com.dpy.appmvdpy.Models.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

/**
 *
 * @author Lilli
 */
@Component
@Scope(value="request")
public class UsersValidator extends DefaultValidator<Users> {

    
    @Autowired
    public UsersFacade facade;
    
    
    @Override
    public boolean supports(Class<?> type) {
        return Users.class.isAssignableFrom(type);
    }

    @Override
    public void validate(Object o, Errors errors) {
        
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username","required.username", "Nome não informado");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password","required.password", "Senha não informada");
        Users user = (Users)o;       
        
        if(user.getPassword() != null && user.getPassword().length() <= 6)
            errors.rejectValue("password", "lenght.password", "Senha deve conter mais que 6 caracteres");
  
        if(facade.existsUsers(user.getUsername().toString()))
            errors.rejectValue("username", "exists.username", "Nome de usuário ja existe!");
   }   
}
